import { useEffect, useState } from 'react';

// 1. 事件监听与清理
function WindowResizeDemo() {
  const [width, setWidth] = useState(window.innerWidth);
  useEffect(() => {
    function handleResize() {
      setWidth(window.innerWidth);
    }
    window.addEventListener('resize', handleResize);
    return () => {
      window.removeEventListener('resize', handleResize);
    };
  }, []);
  return <div>窗口宽度：{width}px</div>;
}

// 2. 数据请求（模拟）
function FetchDemo() {
  const [data, setData] = useState(null);
  useEffect(() => {
    // 模拟异步请求
    const timer = setTimeout(() => {
      setData('这里是异步获取的数据');
    }, 1500);
    return () => clearTimeout(timer);
  }, []);
  return <div>{data ? data : '加载中...'}</div>;
}

// 3. 依赖变化时执行
function DepDemo() {
  const [count, setCount] = useState(0);
  const [msg, setMsg] = useState('');
  useEffect(() => {
    setMsg(`count 变了，现在是 ${count}`);
  }, [count]);
  return (
    <div>
      <button onClick={() => setCount(count + 1)}>加一</button>
      <div>{msg}</div>
    </div>
  );
}

export { WindowResizeDemo, FetchDemo, DepDemo };
